package com.xmxsuperstar.app.client.tunnel;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import android.util.Log;

import com.xmxsuperstar.app.CommonConstants;
import com.xmxsuperstar.app.client.ClientConstants;
import com.xmxsuperstar.http.HttpRequestMsg;
import com.xmxsuperstar.http.HttpResponseMsg;

public class HttpTunnelClient {

    private String tunnelHost;
    private int    tunnelPort;

    public HttpTunnelClient(String tunnelHost, int tunnelPort) {
        this.tunnelHost = tunnelHost;
        this.tunnelPort = tunnelPort;
    }

    public HttpResponseMsg request(String host, int port, boolean isSecure, HttpRequestMsg reqMsg) {
        try {
            reqMsg.setVersion(CommonConstants.HTTP_VERSION);

            String _host = host;
            if ((isSecure && port != 443) || (!isSecure && port != 80)) {
                _host = host + ":" + port;
            }
            reqMsg.addHeader("HOST", _host);

            Socket socket = new Socket(tunnelHost, tunnelPort);
            socket.setSoTimeout(1000 * 60);

            GZIPOutputStream gout = new GZIPOutputStream(socket.getOutputStream());
            ObjectOutputStream out = new ObjectOutputStream(gout);

            out.writeObject(reqMsg);

            out.writeBoolean(isSecure);
            out.writeObject(host);
            out.writeInt(port);

            out.flush();
            gout.finish();

            ObjectInputStream in = new ObjectInputStream(new GZIPInputStream(
                socket.getInputStream()));

            HttpResponseMsg resMsg = (HttpResponseMsg) in.readObject();

            socket.close();

            return resMsg;

        } catch (IOException e) {
            Log.e(ClientConstants.LogTag, e.getMessage());
        } catch (ClassNotFoundException e) {
            Log.e(ClientConstants.LogTag, e.getMessage());
        }
        return null;
    }
}
